package net.huashitong.Project.web;

import com.sirdc.modules.core.filter.Paging;
import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.utils.NumberUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Project.entity.EarlyWarningNode;
import net.huashitong.Project.entity.NewProjects;
import net.huashitong.Project.entity.ProIndustryType;
import net.huashitong.Project.filter.NewProjectsFilter;
import net.huashitong.Project.responseModel.EachNodeDetailModel;
import net.huashitong.Project.responseModel.NodeEffecModel;
import net.huashitong.Project.responseModel.ProcessResultModel;
import net.huashitong.Project.service.*;
import net.huashitong.Project.util.EffecComparator;
import net.huashitong.Project.util.MessageUtil;
import net.huashitong.node.entity.NodeNewschedules;
import net.huashitong.node.entity.NodeNewtemplet;
import net.huashitong.node.service.NodeNewschedulesService;
import net.huashitong.node.service.NodeNewtempletService;
import net.huashitong.node.utile.DateUtil;
import net.huashitong.node.utile.NodeNewschedulesUtil;
import net.huashitong.user.entity.BnpUser;
import net.huashitong.user.service.BnpUserService;
import net.huashitong.user.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.*;

import static net.huashitong.Project.util.TimeDataDealWithUtil.kexuejishu;
import static net.huashitong.utils.UtilsTools.getClientIp;

/**
 * 新的项目模版
 *
 * @author Administrator
 */
@Controller
@RequestMapping("/app/newProject/")
public class NewProjectController extends JsonBaseController {
    public static final String EARLY = "2";     //超前
    public static final String DELAY = "1";     //逾期
    public static final String NORMAL = "0";    //正常
    public static final String NOFINISH = "-1";  //未开始
    @Autowired
    private NewProjectsService newProjectsService;
    @Autowired
    private NodeNewtempletService nodeNewtempletService;
    @Autowired
    private NodeNewschedulesService nodeNewschedulesService;
    @Autowired
    private ProIndustryTypeService proIndustryTypeService;
    @Autowired
    private BnpUserService bus;
    @Autowired
    private MessageService ms;
    @Autowired
    private EarlyWarningNodeService earlyWarningNodeService;
    @Autowired
    private NodeNewschedulesProcess nodeNewschedulesProcess;
    @Autowired
    private NewEarlyWarningService newEarlyWarningService;
    @Autowired
    private InvestCatalogService investCatalogService;
    @Autowired
    private MessageUtil mu;

    @Override
    protected String getView(String s) {
        return null;
    }

    /**
     * 创建项目
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping("/addProject")
    public Message addProject(@RequestBody NewProjectsFilter filter) {
        NewProjects np = new NewProjects();
        np.setName(filter.getName());
        np.setResDept(filter.getResDept());
        np.setResUser(filter.getResUser());
        np.setNatureType(filter.getNatureType());
        np.setMoney(filter.getMoney());
        np.setAddress(filter.getAddress());
        np.setDescribes(filter.getDescribes());
        np.setContactName(filter.getContactName());
        np.setContactPhone(filter.getContactPhone());
        np.setIndustryType(filter.getIndustryType());
        np.setProjectType(filter.getProjectType());
        np.setSchedCode(filter.getSchedCode());
        np.setUserId(filter.getUserId());
        np.setStatus("0");
        newProjectsService.save(np);
        final String projectId = np.getSysId();
        final String natureType = filter.getNatureType();
        final String projectName = np.getName();
        new Thread() {
            public void run() {
                List<NodeNewschedules> nnsList = new ArrayList<NodeNewschedules>();
                //修改新增选项的模版判断
                if ("3".equals(natureType) || "4".equals(natureType)) {
                    List<NodeNewtemplet> nntList = nodeNewtempletService.queryNodeNewtempletByNodeType("0");
                } else {
                    List<NodeNewtemplet> nntList = nodeNewtempletService.queryNodeNewtempletByNodeType(natureType);
                    for (NodeNewtemplet nt : nntList) {
                        NodeNewschedules nns = new NodeNewschedules();
                        nns.setNodeIds(nt.getNodeIds());
                        nns.setNodeId(nt.getNodeId());
                        nns.setPreNodeId(nt.getPreNodeId());
                        nns.setNodeName(nt.getNodeName());
                        nns.setResDept(nt.getResDept());
                        nns.setResUser(nt.getResUser());
                        nns.setResUserPhone(nt.getResUserPhone());
                        nns.setOperatorUser(nt.getOperatorUser());
                        nns.setOperatorPhone(nt.getOperatorPhone());
                        nns.setType(nt.getType());
                        nns.setNodeType(nt.getNodeType());
                        nns.setPlanTime(nt.getPlanTime());
                        nns.setFactTime("0");
                        nns.setFactFinishDate(nt.getFactFinishDate());
                        nns.setPlanBeginDate(nt.getPlanBeginDate());
                        nns.setStatus(nt.getStatus());
                        nns.setState(nt.getState());
                        nns.setProjectId(projectId);
                        nns.setIsDelay("0");
                        nnsList.add(nns);
                        if (ObjectUtils.isNotBlank(nns.getOperatorUser()) && ObjectUtils.isNotBlank(nns.getOperatorPhone()) && "1".equals(nns.getType())) {
                            Map<String, Object> ma = mu.confirmTaskMessage(nns.getOperatorUser(), nns.getOperatorPhone(), "《" + projectName + "》", nns.getNodeId());
                            if ("0".equals(ma.get("code").toString())) {
                                net.huashitong.user.entity.Message m = new net.huashitong.user.entity.Message();
                                m.setRecipients(nns.getOperatorUser());
                                m.setText(ma.get("text").toString());
                                m.setType("0");
                                m.setPhone(nns.getOperatorPhone());
                                m.setMsg(ma.get("msg").toString());
                                m.setProjectName(projectName);
                                m.setResDept(nns.getResDept());
                                ms.save(m);
                            }
                        }
                    }
                }
                nodeNewschedulesService.batchSave(nnsList);
            }

            ;
        }.start();
        return coverMessage("200", "创建成功");
    }

    /**
     * 获取项目类型列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/queryIndustryTypeList")
    public Message queryIndustryTypeList() {
        List<ProIndustryType> list = proIndustryTypeService.query();
        List<Map<String, Object>> List1 = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> List2 = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> List3 = new ArrayList<Map<String, Object>>();
        Map<String, Object> maps = new HashMap<String, Object>();
        for (ProIndustryType pt : list) {
            Map<String, Object> jzMap = new HashMap<String, Object>();
            if ("1".equals(pt.getType())) {
                jzMap.put("typeName", pt.getTypeName());
                jzMap.put("typeCode", pt.getTypeCode());
                List1.add(jzMap);
            } else if ("2".equals(pt.getType())) {
                jzMap.put("typeName", pt.getTypeName());
                jzMap.put("typeCode", pt.getTypeCode());
                List2.add(jzMap);
            } else if ("3".equals(pt.getType())) {
                jzMap.put("typeName", pt.getTypeName());
                jzMap.put("typeCode", pt.getTypeCode());
                List3.add(jzMap);
            }

        }
        maps.put("industryType", List1);
        maps.put("projectType", List2);
        maps.put("schedCode", List3);
        return coverMessage("200", "获取成功", maps);
    }

    /**
     * 获取单个项目的信息和对应节点信息列表
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping("/queryNewProject")
    public Message queryNewProject(@RequestBody NewProjectsFilter filter) {
        List<Map<String, Object>> List1 = new ArrayList<Map<String, Object>>();
        List<NewProjects> List2 = new ArrayList<NewProjects>();
        Paging p = new Paging();
        p.setCurrentPage(Integer.valueOf(filter.getCurrentPage()));
        filter.setPaging(p);
        String userId = filter.getUserId();
        if (StringUtils.isNotBlank(filter.getUserId()) && "0".equals(filter.getType())) {
            List2 = newProjectsService.queryByfilter(filter);
        } else {
            filter.setUserId("");
            List2 = newProjectsService.queryByfilter(filter);
        }
        if (ObjectUtils.isNotBlank(List2)) {
            for (NewProjects np : List2) {
                if ("1".equals(filter.getType())) {
                    String status = "0";
                    BnpUser bu = bus.getById(userId);
                    List<NodeNewschedules> list2 = nodeNewschedulesService.getByResDeptAndOperatorUser(np.getSysId(), bu.getBranch(), bu.getName(), "");
                    List<NodeNewschedules> list3 = nodeNewschedulesService.getByResDeptAndOperatorUser(np.getSysId(), bu.getBranch(), bu.getName(), "1");

                    if (list3.size() == 0) {
                        status = "0";
                    } else if (list2.size() > list3.size()) {
                        status = "1";
                    } else if (list2.size() == list3.size()) {
                        status = "2";
                    }
                    np.setStatus(status);
                }
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("sysId", np.getSysId());
                map.put("name", np.getName());
                map.put("resDept", np.getResDept());
                map.put("resUser", np.getResUser());
                map.put("contactName", np.getResUser());
                map.put("natureType", np.getNatureType());
                map.put("money", np.getMoney());
                map.put("status", np.getStatus());
                map.put("date", np.getCreateDate());
                List1.add(map);

            }

        }
        return coverMessage("200", "获取成功", List1);

    }

    @ResponseBody
    @RequestMapping("/queryNewProjectAndNodel")
    public Message queryNewProjectAndNodel(@RequestBody NewProjectsFilter filter) {
        Map<String, Object> map = new HashMap<String, Object>();
        NewProjects np = newProjectsService.getById(filter.getSysId());
        map.put("sysId", filter.getSysId());
        map.put("name", np.getName());
        map.put("resDept", np.getResDept());
        map.put("resUser", np.getResUser());
        map.put("natureType", np.getNatureType());
        map.put("money", np.getMoney());
        map.put("status", np.getStatus());
        map.put("address", np.getAddress());
        map.put("describes", np.getDescribes());
        map.put("contactName", np.getContactName());
        map.put("contactPhone", np.getContactPhone());
        ProIndustryType t1 = proIndustryTypeService.queryByTypeCode(np.getIndustryType());
        map.put("industryType", t1.getTypeName());
        ProIndustryType t2 = proIndustryTypeService.queryByTypeCode(np.getProjectType());
        map.put("projectType", t2.getTypeName());
        ProIndustryType t3 = proIndustryTypeService.queryByTypeCode(np.getSchedCode());
        map.put("schedCode", t3.getTypeName());
        List<Map<String, Object>> List1 = new ArrayList<Map<String, Object>>();
        List<NodeNewschedules> list1 = nodeNewschedulesService.queryListByProjectId(np.getSysId(), "1", "", "", "");
        List<NodeNewschedules> listd2 = nodeNewschedulesService.queryListByProjectId(np.getSysId(), "2", "", "", "");
        for (NodeNewschedules nns : list1) {
            List<NodeNewschedules> List2 = new ArrayList<NodeNewschedules>();
            Map<String, Object> map1 = new HashMap<String, Object>();
            map1.put("sysId", nns.getSysId());
            map1.put("nodeId", nns.getNodeId());
            map1.put("preNodeId", nns.getPreNodeId());
            map1.put("nodeName", nns.getNodeName());
            map1.put("resDept", nns.getResDept());
            map1.put("resUser", nns.getResUser());
            map1.put("nodeType", nns.getNodeType());
            map1.put("status", nns.getStatus());
            map1.put("state", nns.getState());
            for (NodeNewschedules nns2 : listd2) {
                if (nns.getNodeId().equals(nns2.getNodeIds()) && "1".equals(nns2.getState())) {
                    List2.add(nns2);
                }

            }
            map1.put("childNodesList", List2);
            List1.add(map1);
        }
        map.put("lists", List1);
        return coverMessage("200", "获取成功", map);
    }

    @ResponseBody
    @RequestMapping("/queryNodel")
    public Message queryNodel(@RequestBody NewProjectsFilter filter) {
        Map<String, Object> map = new HashMap<String, Object>();
        NewProjects np = newProjectsService.getById(filter.getSysId());
        map.put("sysId", np.getSysId());
        map.put("name", np.getName());
        map.put("resDept", np.getResDept());
        map.put("resUser", np.getResUser());
        map.put("natureType", np.getNatureType());
        map.put("money", np.getMoney());
        map.put("status", np.getStatus());
        map.put("address", np.getAddress());
        map.put("describes", np.getDescribes());
        map.put("contactName", np.getContactName());
        ProIndustryType t1 = proIndustryTypeService.queryByTypeCode(np.getIndustryType());
        map.put("industryType", t1.getTypeName());
        ProIndustryType t2 = proIndustryTypeService.queryByTypeCode(np.getProjectType());
        map.put("projectType", t2.getTypeName());
        ProIndustryType t3 = proIndustryTypeService.queryByTypeCode(np.getSchedCode());
        map.put("schedCode", t3.getTypeName());
        BnpUser bu = bus.getById(filter.getUserId());
        System.out.println("pid=" + filter.getSysId());
        System.out.println("Branch=" + bu.getBranch());
        System.out.println("name=" + bu.getName());
        List<NodeNewschedules> list1 = nodeNewschedulesService.queryListByProjectId(filter.getSysId(), "1", bu.getBranch(), "", bu.getName());

        map.put("lists", list1);
        return coverMessage("200", "获取成功", map);
    }

    @ResponseBody
    @RequestMapping("/updateNewProject")
    public Message updateNewProject(@RequestBody NewProjectsFilter filter, HttpServletRequest request) {
        String ip = getClientIp(request);
        BnpUser user = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        NewProjects np = newProjectsService.getById(filter.getSysId());
        np.setStatus("1");
        newProjectsService.update(np, ip, user);
        return coverMessage("200", "确认成功");
    }

    /**
     * 开工率图表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/openRate")
    public Message openRate() {
        Map<String, Object> map = newProjectsService.getStarOrNotWorkMap(null);
        return coverMessage("200", "获取成功", map);
    }

    /**
     * 计划新开工项目
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/planeOpenProject")
    public Message planeOpenProject() {
        Map<String, Object> map = newProjectsService.getStarOrNotWorkMap("2001");
        return coverMessage("200", "获取成功", map);
    }

    /**
     * 结转项目
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/jzProject")
    public Message jzProject() {
        Map<String, Object> map = newProjectsService.getStarOrNotWorkMap("2002");
        return coverMessage("200", "获取成功", map);
    }

    /**
     * 二级页面
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/chart2PlaneNewProject")
    public Message chart2PlaneNewProject(@RequestParam(required = false, value = "projectType") String projectType,
                                         @RequestParam(required = false, value = "name") String name,
                                         @RequestParam(required = false, value = "sysId") String sysId,
                                         @RequestParam(required = false, value = "status") String status) {
        NewProjectsFilter filter = new NewProjectsFilter();
        System.out.println("###############3#######################projectType=" + projectType);
        if (!"1".equals(projectType)) {
            filter.setProjectType(projectType);
        }
        filter.setName(name);
        filter.setSysId(sysId);
        filter.setStatus(status);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        List<NewProjects> projects = newProjectsService.getProjectInfo2(filter);
        for (NewProjects project : projects) {
            Map<String, Object> map = new HashMap<String, Object>();
            //项目sysId
            map.put("sysId", project.getSysId());
            //项目名
            map.put("name", project.getName());
            //分管领导
            map.put("resUser", project.getResUser());
            //责任单位
            map.put("resDept", project.getResDept());
            //项目完成率
            String completionRate = nodeNewschedulesService.getNodeCompletionRate(project.getSysId());
            map.put("completionRate", completionRate);

            list.add(map);
        }
        Collections.sort(list, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> p1, Map<String, Object> p2) {
                NumberFormat nf = NumberFormat.getPercentInstance();
                String data = p1.get("completionRate") + "";
                String data2 = p2.get("completionRate") + "";
                try {
                    // 将百分数转换成Number类型
                    Number m = nf.parse(data);
                    Number m2 = nf.parse(data2);
                    double dd = m.doubleValue();
                    double dd2 = m2.doubleValue();
                    if (dd == dd2) {
                        return 0;
                    } else if (dd > dd2) {
                        return -1;
                    } else {
                        return 1;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return 1;
            }
        });
        System.out.println("list=" + list.size());
        return coverMessage("200", "获取成功", list);
    }

    /**
     * 二级页面_点击具体项目后右边详情
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/chart2PlaneNewProjectDetail")
    public Message chart2PlaneNewProjectDetail(@RequestParam("id") String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        NewProjects project = newProjectsService.getById(id);
        List<NodeNewschedules> bigNodeList = nodeNewschedulesService.getNeedBigNodeByProjectId(id);
        List<NodeNewschedules> allNodeNewschedules = nodeNewschedulesService.getNodeByProjectId(id);
        //各个节点时间
        List<Map<String, Object>> eachNodeTime = new ArrayList<Map<String, Object>>();
        //项目名
        map.put("name", project.getName());
        //责任单位
        map.put("resDept", project.getResDept());
        //启动时间
        String createDate = StringUtils.isBlank(project.getPlanBeginDate()) ? "" : project.getPlanBeginDate().replace("-", ".");
        map.put("createDate", createDate);
        //项目计划完成天数
        int planCompleteDays = 0;
        //超前节点数量
        int advance = 0;
        //正常节点数量
        int normal = 0;
        //延期节点数量
        int delayed = 0;
        //进行中
        int underway = 0;
        //超前节点List
        List<Map<String, Object>> advanceList = new ArrayList<Map<String, Object>>();
        //正常节点List
        List<Map<String, Object>> normalList = new ArrayList<Map<String, Object>>();
        //逾期节点List
        List<Map<String, Object>> delayedList = new ArrayList<Map<String, Object>>();
        //未开始节点List
        List<Map<String, Object>> notBeginList = new ArrayList<Map<String, Object>>();
        //进行中节点List
        List<Map<String, Object>> underwayList = new ArrayList<Map<String, Object>>();
        //遍历大节点
        for (NodeNewschedules bigNode : bigNodeList) {
            Map<String, Object> timeMap = new HashMap<String, Object>();
            timeMap.put("bigNodeName", bigNode.getNodeName());
            timeMap.put("planTime", bigNode.getPlanTime());
            timeMap.put("factTime", bigNode.getFactTime());
            timeMap.put("nodeId", bigNode.getNodeId());
            timeMap.put("completionStatus", "notBegin");
            notBeginList.add(timeMap);
            int factTime = Integer.parseInt(StringUtils.isBlank(bigNode.getFactTime()) ? "0" : bigNode.getFactTime());
            int planTime = Integer.parseInt(StringUtils.isBlank(bigNode.getPlanTime()) ? "0" : bigNode.getPlanTime());
            if (factTime == 0) {
                // 遍历小节点，查找任意小节点状态不为0时（已开始或已完成），删除未开始节点Map中的对应项，之后跳出此循环。

                for (NodeNewschedules nodeNewschedule : allNodeNewschedules) {
                    if (nodeNewschedule.getNodeIds().equals(bigNode.getNodeId())) {
                        if (!"0".equals(nodeNewschedule.getStatus())) {
                            notBeginList.remove(timeMap);
                            if ("1".equals(nodeNewschedule.getStatus())) {
                                underway++;
                                timeMap.put("completionStatus", "underway");
                                underwayList.add(timeMap);
                                break;
                            }

                        }
                    }
                }

            } else if (factTime == planTime) {
                normal++;
                timeMap.put("completionStatus", "normal");
                notBeginList.remove(timeMap);
                normalList.add(timeMap);
            } else if (factTime < planTime) {
                advance++;
                timeMap.put("completionStatus", "advance");
                notBeginList.remove(timeMap);
                advanceList.add(timeMap);
            } else {
                delayed++;
                timeMap.put("completionStatus", "delayed");
                notBeginList.remove(timeMap);
                delayedList.add(timeMap);
            }
            //如果计划时间没空，则返回0
            planCompleteDays += Integer.parseInt(StringUtils.isBlank(bigNode.getPlanTime()) ? "0" : bigNode.getPlanTime());
            eachNodeTime.add(timeMap);
        }
        map.put("planCompleteDate", DateUtil.addDays(createDate, planCompleteDays));
        //完成的小节点数
        int completeNode = nodeNewschedulesService.getNodeCompletionOrNotNum(id, "2");
//        normal = completeNode;
        map.put("completeNode", completeNode);
        //所有的小节点数
        int totalNode = nodeNewschedulesService.getNodeCompletionOrNotNum(id, null);
        map.put("totalNode", totalNode);
        //项目完成率
        String completionRate = nodeNewschedulesService.getNodeCompletionRate(id);
        map.put("completionRate", completionRate);
        map.put("eachNodeTime", eachNodeTime);
        map.put("advanceList", advanceList);
        map.put("normalList", normalList);
        map.put("delayedList", delayedList);
        map.put("notBeginList", notBeginList);
        map.put("underwayList", underwayList);
        map.put("advance", advance);
        map.put("normal", normal);
        map.put("delayed", delayed);
        map.put("underway", underway);
        map.put("notBegin", notBeginList.size());
        map.put("projectId", id);
        return coverMessage("200", "获取成功", map);
    }


    @ResponseBody
    @RequestMapping("/appNewIndex")
    public Message appNewIndex() {
        Map<String, Object> map = new HashMap<String, Object>();
        //新开工率
        Map<String, Object> map1 = newProjectsService.getStarOrNotWorkMap("2001");
        map1.put("centerDataCode", "2001");
        map1.put("cSXTitle", "0");
        //结转率
        Map<String, Object> map2 = newProjectsService.getStarOrNotWorkMap("2002");
        map2.put("centerDataCode", "2002");
        map2.put("cSXTitle", "0");
        //行业数
        Map<String, Object> map3 = newProjectsService.queryIndustryInfo();
        //开工率
        Map<String, Object> map4 = newProjectsService.getStarOrNotWorkMap(null);
        //进度分类
        List<NewProjectsFilter> list = newProjectsService.queryScheduleInfo();
        List<Map> workList = new ArrayList<Map>();

        Map<String, Object> map5 = new HashMap<String, Object>();
        List<NewProjects> projects = null;
        NewProjectsFilter filter = new NewProjectsFilter();
        //重点项目
        //projects = newProjectsService.getProjectInfo(filter);
        projects = newProjectsService.query();
        int focusProject = projects.size();
        //计划投资
        double plannedInvestment = 0;
        for (NewProjects project : projects) {
            System.out.println("project=" + project.getName());
            System.out.println("Money=" + project.getMoney());
            plannedInvestment += Double.parseDouble(project.getMoney());
        }
        //转不了，需要安卓端做处理
//        DecimalFormat decimalFormat = new DecimalFormat("###,###.00");
//        double value = Double.valueOf(kexuejishu(NumberUtils.doubleFormat(plannedInvestment, 2)+"")).doubleValue();

        map4.put("plannedInvestment", kexuejishu(NumberUtils.doubleFormat(plannedInvestment, 2) + ""));
        map4.put("focusProject", focusProject);
//        map1.put("plannedInvestment",plannedInvestment);
//        map2.put("plannedInvestment",plannedInvestment);
        //年度投资计划(暂时写死)
//        double annualInvestmentPlan = 150;
        //计划新开工项目年度计划投资
        double planeProjectAnnualPlan = 0;
        filter.setProjectType("2001");//计划新开工项目
        projects = newProjectsService.getProjectInfo(filter);
        for (NewProjects project : projects) {
            planeProjectAnnualPlan += Double.parseDouble(project.getMoney());
        }
        //结转项目年度计划投资
        double jzProjectAnnualPlan = 0;
        filter.setProjectType("2002");//结转项目
        projects = newProjectsService.getProjectInfo(filter);
        for (NewProjects project : projects) {
            jzProjectAnnualPlan += Double.parseDouble(project.getMoney());
        }
//        map5.put("focusProject", focusProject);
//        map5.put("plannedInvestment", plannedInvestment);
////        map.put("annualInvestmentPlan", annualInvestmentPlan);
//        map5.put("planeProjectAnnualPlan", planeProjectAnnualPlan);
//        map5.put("jzProjectAnnualPlan", jzProjectAnnualPlan);

        workList.add(map1);
        workList.add(map2);
        map.put("centerDataList", workList);
        map.put("industryList", map3.get("industry"));
        map.put("schedList", list);
        map.put("focusProject", map4.get("focusProject"));
        map.put("notStartWorkNum", map4.get("notStartWorkNum"));
        map.put("notStartWorkRate", map4.get("notStartWorkRate"));
        map.put("plannedInvestment", map4.get("plannedInvestment"));
        map.put("startWorkNum", map4.get("startWorkNum"));
        map.put("startWorkRate", map4.get("startWorkRate"));

        return coverMessage("200", "获取成功", map);
    }

    /**
     * 获取全部项目
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping("/allProject")
    public Message allProject(@RequestBody NewProjectsFilter filter) {
        List<Map<String, Object>> allMapList = new ArrayList<Map<String, Object>>();
        List<NewProjects> allList = newProjectsService.getProjectInfo(filter);
        for (NewProjects np : allList) {
            int moneyList = 0;
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("projectName", np.getName());
            map.put("sysId", np.getSysId());         //项目id
            map.put("resUser", np.getResUser());     //分管领导
            map.put("resDept", np.getResDept());     //责任单位
            map.put("status", np.getStatus());
            map.put("planBeginDate", np.getPlanBeginDate());//开始时间
            List<NodeNewschedules> list2 = nodeNewschedulesService.getNodeInfo(np.getSysId(), "2", "", "1");
            map.put("smallTotal", list2.size());//小节点总数
            int smallFinishTotal = 0;//已完成节点数目
            int ongoingTotal = 0;//进行中
            int unfinishedTotal = 0;//未完成
            int planTimeTotal = 0;//
            String palnFinishTime = "";
            for (NodeNewschedules nd : list2) {
                if ("0".equals(nd.getStatus())) {
                    unfinishedTotal++;
                } else if ("1".equals(nd.getStatus())) {
                    ongoingTotal++;
                } else if ("2".equals(nd.getStatus())) {
                    smallFinishTotal++;
                }
                if (ObjectUtils.isBlank(nd.getPlanTime())) {
                    nd.setPlanTime("0");
                }
                planTimeTotal = planTimeTotal + Integer.parseInt(nd.getPlanTime());
            }
            palnFinishTime = DateUtil.addDays(np.getPlanBeginDate(), planTimeTotal);
            map.put("smallFinishTotal", smallFinishTotal);
            map.put("ongoingTotal", ongoingTotal);
            map.put("unfinishedTotal", unfinishedTotal);
            map.put("planFinishDate", palnFinishTime);
            map.put("percent", NumberUtils.doubleFormat(smallFinishTotal * (1.0) / list2.size(), 4));
            allMapList.add(map);
        }
        return coverMessage("200", "获取成功", allMapList);
    }

    /**
     * 二级页面右下角接口，通过项目ID和大节点ID查询对应的小节点
     *
     * @param projectId 项目sysId
     * @param nodeId    节点ID（大）
     * @return
     */
    @ResponseBody
    @RequestMapping("/querySmallNodes")
    public Message querySmallNodes(@RequestParam("projectId") String projectId, @RequestParam("nodeId") String nodeId) {
        Map<String, Object> map = new HashMap<String, Object>();
        NewProjects n = newProjectsService.getById(projectId);
        List<NodeNewschedules> smallNodes = nodeNewschedulesService.getNode2(nodeId, projectId);
        int totalFactTime = 0;
        for (NodeNewschedules smallNode : smallNodes) {
            if ("2".equals(smallNode.getState())) {
                smallNodes.remove(smallNode);
            } else if (Objects.equals("2", smallNode.getStatus())) {
                System.out.print("#######" + smallNode.getNodeId());
                if ("".equals(smallNode.getFactTime())) {
                    smallNode.setFactTime("0");
                }
                totalFactTime += Integer.parseInt(smallNode.getFactTime());
            }
            if ("业主单位".equals(smallNode.getResDept()) ||
                    "中介机构".equals(smallNode.getResDept()) ||
                    "业主、中介机构".equals(smallNode.getResDept())) {
                smallNode.setResDept(n.getResDept());
            }
        }
        map.put("smallNodes", smallNodes);
        map.put("totalFactTime", totalFactTime);
        return coverMessage("200", "小节点获取成功", map);
    }

    @ResponseBody
    @RequestMapping("/getAllDeptCompletionRate")
    public Message getAllDeptCompletionRate() {
        Map<String, Object> map = nodeNewschedulesService.getAllDeptNodeCompletionRate();
        return coverMessage("200", "各单位节点完成率获取成功", map);
    }

    @ResponseBody
    @RequestMapping("/getEarlyWarningHandleRate")
    public Message getEarlyWarningHandleRate() {
        Map<String, Object> map = earlyWarningNodeService.queryEarlyWarningStateByDept();
        return coverMessage("200", "各单位预警信息处理率获取成功", map);
    }

    /*
     * app项目总结(进程报告)
     */
    @ResponseBody
    @RequestMapping(value = "summarize")
    public Message summarize(HttpServletRequest request) {
        List<EachNodeDetailModel> eachNodeDetailModels = new ArrayList<EachNodeDetailModel>();
        Map<String, Object> map = new HashMap<String, Object>();
        String projectId = request.getParameter("projectId");
        NewProjects newProject = newProjectsService.getById(projectId);
        List<NodeNewschedules> nodeList = nodeNewschedulesService.getNodeByProjectId(projectId);
//      int timeNum = DateUtil.betweenTwoDateNum(newProject.getFinishTime(), newProject.getPalnFinishTime());
        Map<String, String> bigNodeMap = new HashMap<String, String>();


        int totalPlanTime = 0;//计划时间累计
        int totalFactTime = 0;//实际用时累计
        int finishNodeNum = 0;//完成节点
        int leadingNodeNum = 0;//超前节点
        int normalNodeNum = 0;//正常节点
        int delayNodeNum = 0;//延期节点

        List<NodeNewschedules> bigNodeList = new ArrayList<NodeNewschedules>();
        List<NodeNewschedules> smallNodeList = new ArrayList<NodeNewschedules>();
        List<String> nodeListStr = new ArrayList<String>();
        List<NodeNewschedules> allNode = new ArrayList<NodeNewschedules>();


        //需要的所有小节点
        List<NodeNewschedules> allNode1 = new ArrayList<NodeNewschedules>();
        for (NodeNewschedules node : nodeList) {
            //统计小节点完成数
            if ("1".equals(node.getStatus()) && "2".equals(node.getType())) {
                finishNodeNum++;
                allNode.add(node);
            }
            if ("1".equals(node.getState()) && "2".equals(node.getType())) {
                allNode1.add(node);
            }
            //大节点
            if ("1".equals(node.getType())) {
                System.out.println("NodeId=" + node.getNodeId());
                System.out.println("tPlanTime=" + node.getPlanTime());
                totalPlanTime += (StringUtils.isNotBlank(node.getPlanTime()) ? Integer.parseInt(node.getPlanTime()) : 0);
                totalFactTime += (StringUtils.isNotBlank(node.getFactTime()) ? Integer.parseInt(node.getFactTime()) : 0);
                bigNodeList.add(node);
                bigNodeMap.put(node.getNodeId(), node.getNodeName());

                //小节点
            } else if ("2".equals(node.getType())) {
                smallNodeList.add(node);
            }
        }

        //节点工具类
        NodeNewschedulesUtil nodeUtil = new NodeNewschedulesUtil();
        nodeUtil.updateNodesTimeState(smallNodeList, newProject);

        for (NodeNewschedules bigNodes : bigNodeList) {
            //cq=超前数，zc=正常数，yq=延期数
            int cq = 0;
            int zc = 0;
            int yq = 0;
            //大节点实际用时数
            int bigFactTime = 0;
            for (NodeNewschedules smallNodes : smallNodeList) {
                if (smallNodes.getNodeId().split("\\.")[0].equals(bigNodes.getNodeId())) {
                    if ("2".equals(smallNodes.getStatus())) {

                    }
                    //0正常 1 逾期，2 超前
                    if (NORMAL.equals(smallNodes.getIsDelay())) {
                        zc = 1;
                    } else if (DELAY.equals(smallNodes.getIsDelay())) {
                        yq = 1;
                    } else if (EARLY.equals(smallNodes.getIsDelay())) {
                        cq = 1;
                    }
                    bigFactTime += StringUtils.isNotBlank(smallNodes.getFactTime()) ? Integer.parseInt(smallNodes.getFactTime()) : 0;
                }
            }
            bigNodes.setFactTime(bigFactTime + "");
            if (cq == 0 && yq == 0 && zc == 1) {
                bigNodes.setIsDelay(NORMAL);
                normalNodeNum++;
            } else {
                if (yq == 1) {
                    bigNodes.setIsDelay(DELAY);
                    delayNodeNum++;
                } else {
                    if (cq == 1) {
                        bigNodes.setIsDelay(EARLY);
                        leadingNodeNum++;
                    } else {
                        bigNodes.setIsDelay(NORMAL);
                        normalNodeNum++;
                    }
                }
            }
        }
        finishNodeNum = leadingNodeNum + normalNodeNum + delayNodeNum;
        System.out.println(leadingNodeNum + " " + finishNodeNum);
        double leadingRate = NumberUtils.doubleFormat(finishNodeNum != 0 ? (leadingNodeNum * 1.0 / finishNodeNum) : 0, 2);
        double normalNodeRate = NumberUtils.doubleFormat(finishNodeNum != 0 ? (normalNodeNum * 1.0 / finishNodeNum) : 0, 2);
        double delayNodeRate = NumberUtils.doubleFormat(finishNodeNum != 0 ? (delayNodeNum * 1.0 / finishNodeNum) : 0, 2);

        List<String> nodeList1 = new ArrayList<String>();
        for (NodeNewschedules node : allNode1) {
            if (!nodeList1.contains(node.getNodeIds()) && !"0".equals(node.getNodeIds()) && "2".equals(node.getStatus())) {
                nodeList1.add(node.getNodeIds());
            }
        }
        Map<String, EachNodeDetailModel> nodesMap = new HashMap<String, EachNodeDetailModel>();
        //所有节点
        System.out.println("zong111=" + nodeList1.size());
        for (String node : nodeList1) {
            int factTime = 0;   //实际时间
            int planTime = 0;   //计划时间
            for (NodeNewschedules n : allNode1) {
                if ("2".equals(n.getStatus()) && node.equals(n.getNodeIds()) && StringUtils.isNotBlank(n.getFactTime())) {
                    factTime = factTime + Integer.parseInt(n.getFactTime());
                }
                if ("2".equals(n.getStatus()) && node.equals(n.getNodeIds()) && StringUtils.isNotBlank(n.getPlanTime())) {
                    planTime = planTime + Integer.parseInt(n.getPlanTime());
                }
            }

            EachNodeDetailModel eachNodeDetailModel = new EachNodeDetailModel();
            eachNodeDetailModel.setFactTime(factTime);
            eachNodeDetailModel.setPlanTime(planTime);
            eachNodeDetailModel.setTimeState(planTime - factTime);    //正数表示超前；0表示正常；负数表示逾期
            eachNodeDetailModel.setNodeId(node);
            eachNodeDetailModel.setProjectId(projectId);
            eachNodeDetailModel.setNode1Name(bigNodeMap.get(node));
            nodesMap.put(node, eachNodeDetailModel);
            eachNodeDetailModels.add(eachNodeDetailModel);
        }
        List<NodeEffecModel> nodeEffecList = new ArrayList<NodeEffecModel>();

        for (EachNodeDetailModel model : eachNodeDetailModels) {
            int ft = model.getFactTime();
            int pt = model.getPlanTime();
            String name = model.getNode1Name();
            DecimalFormat df = new DecimalFormat("##0.00");
            if (pt == 0) {
                continue;
            }
            double res = NumberUtils.doubleFormat((double) (pt - ft) / pt, 4);
            NodeEffecModel nodeEffec = new NodeEffecModel(model.getTimeState(), model.getNodeId(), res);
            nodeEffec.setName(name);
            nodeEffecList.add(nodeEffec);
        }

        Collections.sort(nodeEffecList, new EffecComparator());

        List<Map<String, Object>> gxlList = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> dxlList = new ArrayList<Map<String, Object>>();

//        myprint(nodeEffecList);
        List<NodeEffecModel> hightEffect = new ArrayList<NodeEffecModel>();
        List<NodeEffecModel> lowEffect = new ArrayList<NodeEffecModel>();
        Map<String, List<NodeEffecModel>> effecListMap = new HashMap<String, List<NodeEffecModel>>();
        if (ObjectUtils.isNotBlank(nodeEffecList)) {
            for (int i = 0; i < 3; i++) {
                Map<String, Object> xlMap = new HashMap<String, Object>();
                hightEffect.add(nodeEffecList.get(i));
                xlMap.put("gxljd", nodeEffecList.get(i).getNodeId() + ". " + nodeEffecList.get(i).getName()
                        + "(用时占比：" + NumberUtils.doubleFormat(nodeEffecList.get(i).getPercent() * 100, 1) + "%" + ")");
                gxlList.add(xlMap);
            }
            for (int i = nodeEffecList.size() - 1; i > nodeEffecList.size() - 4; i--) {
                Map<String, Object> xlMap = new HashMap<String, Object>();
                lowEffect.add(nodeEffecList.get(i));
                xlMap.put("gxljd", nodeEffecList.get(i).getNodeId() + ". " + nodeEffecList.get(i).getName()
                        + "(用时占比：" + NumberUtils.doubleFormat(nodeEffecList.get(i).getPercent() * 100, 1) + "%" + ")");
                dxlList.add(xlMap);

            }
        } else {
            Map<String, Object> xlMap = new HashMap<String, Object>();
            xlMap.put("gxljd", "暂无");
            gxlList.add(xlMap);
            dxlList.add(xlMap);

        }
        effecListMap.put("hightEffect", hightEffect);//效率最高
        effecListMap.put("lowEffect", lowEffect);    //效率最低

        //项目信息
        map.put("projectName", newProject.getName());
        map.put("resDept", newProject.getResDept());
        map.put("beginTime", newProject.getPlanBeginDate());
        map.put("planFinishTime", newProject.getFactFinishDate());
        //项目状态
        if ("4".equals(newProject.getStatus())) {
            if (totalFactTime > totalPlanTime) {    //总的实际用时 > 总的计划用时 = 逾期
                map.put("status", "逾期");
                map.put("dateNum", Math.abs(totalFactTime - totalPlanTime));
            } else if (totalFactTime == totalPlanTime) {
                map.put("status", "正常");
                map.put("dateNum", Math.abs(0));
            } else {
                map.put("status", "超前");
                map.put("dateNum", Math.abs(totalPlanTime - totalFactTime));
            }
        } else if ("1".equals(newProject.getStatus())) {
            map.put("status", "正常");
            map.put("dateNum", Math.abs(0));
        } else if ("2".equals(newProject.getStatus())) {
            map.put("status", "正常");
            map.put("dateNum", Math.abs(0));
        } else if ("3".equals(newProject.getStatus())) {
            map.put("status", "正常");
            map.put("dateNum", Math.abs(0));
        } else if ("5".equals(newProject.getStatus())) {
            map.put("status", "正常");
            map.put("dateNum", Math.abs(0));
        }
        //节点完成情况个数
        map.put("finishNodeNum", finishNodeNum);
        map.put("leadingNodeNum", leadingNodeNum);
        map.put("normalNodeNum", normalNodeNum);
        map.put("delayNodeNum", delayNodeNum);

        //雷达图 概率
        map.put("leadingRate", leadingRate);
        map.put("normalNodeRate", normalNodeRate);
        map.put("delayNodeRate", delayNodeRate);
        Collections.sort(bigNodeList, new Comparator<NodeNewschedules>() {
            @Override
            public int compare(NodeNewschedules node1, NodeNewschedules node2) {
                return Integer.parseInt(node1.getNodeId()) - Integer.parseInt(node2.getNodeId());
            }
        });
        List<Map<String, Object>> nodeMapList = new ArrayList<Map<String, Object>>();
        for (NodeNewschedules node : bigNodeList) {
            Map<String, Object> nodeMap = new HashMap<String, Object>();
            nodeMap.put("nodeState", node.getIsDelay());//大节点状态 0正常 1 逾期，2 超前       -1：未开始
            nodeMap.put("nodeId", node.getNodeId());
            nodeMapList.add(nodeMap);
        }
        map.put("nodeList", nodeMapList);
        map.put("gxlList", gxlList);
        map.put("dxlList", dxlList);

        //部门完成情况
        Map<String, ProcessResultModel> deptNodeMap = new HashMap<String, ProcessResultModel>();
        List<ProcessResultModel> resList = new ArrayList<ProcessResultModel>();

        List<NodeNewschedules> deptList = nodeNewschedulesService.getAllDeptByProId();

        for (NodeNewschedules dept : deptList) {
            ProcessResultModel processResultModel = nodeNewschedulesProcess.getjj(projectId, dept.getResDept());
            if (processResultModel != null) {
                resList.add(processResultModel);
            }
        }
        List<Map<String, Object>> wcqks = new ArrayList<Map<String, Object>>();
        for (ProcessResultModel res : resList) {
            Map<String, Object> wcqk = new HashMap<String, Object>();

            wcqk.put("dept", res.getDept());
            wcqk.put("allNodeNum", res.getAllNode());
            wcqk.put("finishNodeNum", res.getFinished());
            wcqk.put("unFinishNodeNum", res.getNoFinish());
            wcqk.put("leadingNodeNum", res.getBeyond());
            wcqk.put("normalNodeNum", res.getNormal());
            wcqk.put("delayNodeNum", res.getLate());
            wcqk.put("leadingDate", 2);
            wcqk.put("rate", 100);
            wcqks.add(wcqk);
        }
        map.put("wcqkList", wcqks);
        return coverMessage("200", "获取成功", map);
    }

    @ResponseBody
    @RequestMapping(value = "finishProject")
    public Message finishProjectByAll() {
        List<NewProjects> list = newProjectsService.getFinishProject();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("finishProjectList", list);
        return coverMessage("200", "获取成功", map);
    }

//    @ResponseBody
//    @RequestMapping(value = "/warningnumbers", method = RequestMethod.GET)
//    public Message queryWarningNumber(@RequestParam(required = false) String projectId) {
//        Map<String, Integer> s = newEarlyWarningService.queryByWarningNumber(projectId);
//        return coverMessage("200", "获取成功", s);
//    }
//
//    @ResponseBody
//    @RequestMapping(value = "/warningdetail", method = RequestMethod.GET)
//    public Message queryWarningDetail(@RequestParam(required = false) String projectId, @RequestParam String level) {
//        List<EarlyWarningNode> earlyWarningNodeList = newEarlyWarningService.queryWarningDetail(projectId, level);
//        List<Map<String, Object>> list = new ArrayList<>();
//        for(EarlyWarningNode e : earlyWarningNodeList){
//            Map<String, Object> map = new HashMap<>();
//            map.put("nodeId", e.getNodeId());
//            map.put("problem", StringUtils.isBlank(e.getOpinions())?"待处理":e.getOpinions());
//            map.put("nodeTime", e.getUpdDate());
//            list.add(map);
//        }
//        return coverMessage("200", "获取成功", list);
//    }

    @ResponseBody
    @RequestMapping(value = "/warningshort", method = RequestMethod.GET)
    public Message queryWarningDetail(@RequestParam(required = false) String projectId) {
        List<Map> list = new ArrayList<>();
        List<EarlyWarningNode> earlyWarningNodes = newEarlyWarningService.queryByWarningNumberShort(projectId);
        for (EarlyWarningNode earlyWarningNode : earlyWarningNodes) {
            Map<String, Object> map = new HashMap<>();
            map.put("nodeId", earlyWarningNode.getNodeId());
            map.put("problem", StringUtils.isBlank(earlyWarningNode.getOpinions()) ? "待处理" : earlyWarningNode.getOpinions());
            map.put("nodeTime", earlyWarningNode.getUpdDate());
            list.add(map);
        }
        return coverMessage("200", "获取成功", list);
    }

    @ResponseBody
    @RequestMapping(value = "/investCatalog", method = RequestMethod.GET)
    public Message queryWarningDetail() {
        Map map = investCatalogService.queryInvestCatalog();
        return coverMessage("200", "获取成功", map);
    }


    /**
     * 推算节点流程层级关系
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/calculateLevel/{projectId}", method = RequestMethod.GET)
    public Message calculateLevel(@PathVariable String projectId) {
        List<List<String>> list = nodeNewtempletService.calculateLevel(projectId);
        return coverMessage("200", "获取成功", list);
    }
}
